package cn.jdy.plugins.admin;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.persistence.Column;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.plugins.entity.ChatContent;
import cn.jdy.plugins.entity.ChatData;
import cn.jdy.plugins.entity.ExamQuestions;
import cn.jdy.plugins.entity.ChatRobot;
import cn.jdy.plugins.entity.Live;
import cn.jdy.plugins.entity.WatchUser;
import cn.jdy.plugins.entity.WatchUserRobot;
import cn.jdy.plugins.service.ChatContentService;
import cn.jdy.plugins.service.ChatDataService;
import cn.jdy.plugins.service.ChatRobotService;
import cn.jdy.plugins.service.LiveService;
import cn.jdy.plugins.service.WatchUserRobotService;
import cn.jdy.plugins.service.WatchUserService;

/**
 * @title  留言机器人定时设置
 *  @author jga
 * @date 2017-1-26
 */
@Controller
@RequestMapping("/chatRobot")
public class ChatRobotCtrl extends BaseCtrl {
	@Autowired
	private ChatRobotService chatRobotService;
	@Autowired
	private LiveService liveService;
	@Autowired
	private ChatContentService chatContentService;
	@Autowired
	private WatchUserService watchUserService;
	@Autowired
	private ChatDataService chatDataService;
	@Autowired
	private WatchUserRobotService watchUserRobotService;
	/**
	 * 初始化
	 * 
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list(@RequestParam(required = false) Integer s,ChatRobot obj) {
		ModelAndView mv = new ModelAndView("/chatRobot/chatRobotList.jsp");
		if (s != null)
			switch (s) {
			case 1:
				mv.addObject("msg", "保存成功！");
				break;
			case 2:
				mv.addObject("msg", "更新成功！");
				break;
			case 3:
				mv.addObject("msg", "删除成功！");
				break;
			case 4:
				mv.addObject("msg", "操作失败！");
				break;
			default:
				break;
			}
		mv.addObject("data",obj);

		return mv;
	}
	/**
	 * 初始化
	 * 
	 * @return
	 */
	@RequestMapping("/chatRobotllive")
	public ModelAndView chatRobotllive(@RequestParam(required = false) Integer s,ChatRobot obj) {
		ModelAndView mv = new ModelAndView("/chatRobotllive/chatRobotllive.jsp");
		if (s != null)
			switch (s) {
			case 1:
				mv.addObject("msg", "保存成功！");
				break;
			case 2:
				mv.addObject("msg", "更新成功！");
				break;
			case 3:
				mv.addObject("msg", "删除成功！");
				break;
			case 4:
				mv.addObject("msg", "操作失败！");
				break;
			default:
				break;
			}
		mv.addObject("data",obj);

		return mv;
	}
	
	/**
	 * 异步查询
	 * @param visitLog
	 * @return
	 */
	@RequestMapping("/queryByPage")
	@ResponseBody
	public Map<String, Object> queryByPage(ChatRobot obj,String fromDate, String toDate) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("dataList", chatRobotService.query(obj,fromDate,toDate));
			jsonMap.put("iTotalDisplayRecords", chatRobotService.count(obj,fromDate,toDate));
			jsonMap.put("iTotalRecords", chatRobotService.count(obj,fromDate,toDate));
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}

	
	/**
	 * 删除
	 * @return
	 */
	@RequestMapping("/del/{id}")
	@ResponseBody
	public Map<String, Object> del(@PathVariable Long id) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			this.chatRobotService.delete(id);
			this.chatDataService.delete("cahtRobotId", id);
			jsonMap.put("msg", "成功");

		} catch(Exception e) {
			jsonMap.put("dataList", "失败");
			BaseLog.e(getClass(), "删除异常！", e);
		}
		return jsonMap;
	}
	
	/**
	 * 编辑
	 * @param id
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit(ChatRobot obj) {
		ModelAndView mv = new ModelAndView("/chatRobot/chatRobotDetail.jsp");
		
			mv.addObject("datalists",liveService.find("id",obj.getLiveId()));
		mv.addObject("confdata",confService.queryByType(53,null, null));
		mv.addObject("data", obj.getId()==null||obj.getId()==0 ? obj.getId() : this.chatRobotService.find(obj.getId()));
		return mv;
	}

	/**
	 * 保存（更新）
	 * @param Live
	 * @return
	 */
	@RequestMapping("/save")
	public @ResponseBody ModelAndView save(ChatRobot obj) {
		ModelAndView mv = new ModelAndView();
		try {
			if(obj.getId()==null) {
				obj.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				this.chatRobotService.save(obj);
				//mv.setViewName(this.viewName.concat("1"));
	
				mv.setViewName("redirect:/chatRobot/list?liveId="+obj.getLiveId());

			} else {
				obj.setUpdateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				this.chatRobotService.update(obj);
			//	mv.setViewName(this.viewName.concat("2"));
				mv.setViewName("redirect:/chatRobot/list?liveId="+obj.getLiveId());

		
			}
		
		} catch(Exception e) {
			BaseLog.e(getClass(), "保存异常！", e);
		}
		return mv;
	}
	/**
	 * 生成机器留言数据
	 * @param ChatRobot
	 * @return
	 */
	@RequestMapping("/addRobot")
	public @ResponseBody ModelAndView addRobot(ChatRobot obj) {
		ModelAndView mv = new ModelAndView();
		try {
			  obj=chatRobotService.find(obj.getId());
			if(obj.getIsdate()!=null&&"1".equals(obj.getIsdate())) {//已经生成过的
			
				//mv.setViewName(this.viewName.concat("1"));
	
				mv.setViewName("redirect:/chatData/list?cahtRobotId="+obj.getId());

			} else {
	
		    	//生成留言时间开始
				List alist=new ArrayList<>();
		    	for (int i = 0; i < Integer.valueOf(obj.getChatNumber()); i++) {//随机生成留言的时间
		    		 Date date = randomDate(obj.getStartTime(),obj.getEndTime());  
		             alist.add(date);
				}
		    	 Collections.sort(alist);//排序留言时间
		    	//生成留言时间结束
		    	
		    	//生成留言库 开始
		    	String typeid[]=obj.getChattype().split(",");
		    	List<ChatContent> contlist=new ArrayList<ChatContent>();//生成留言库
		    	for (int i = 0; i < typeid.length; i++) {
		    	  List<ChatContent>	clist =chatContentService.find("chatType",typeid[i]);
			    	for (ChatContent c : clist) {
			    		contlist.add(c);
			    		
					}
				}
		      	//生成留言库 结束
		    	
		    	//生成用户开始
		    	int x=1+(int)(Math.random()*100);
		    	WatchUserRobot wu=new WatchUserRobot();
		    	wu.setiDisplayStart(x);
		    	wu.setiDisplayLength(x+300);
		    	List<WatchUserRobot>  listuser =	watchUserRobotService.query(wu);
		      	//生成用户 结束
		    	
		    	//生成机器留言数据开始
		    			 for (int i = 0; i < alist.size(); i++) {
		    				 ChatData cd=new ChatData();
		    				 cd.setCahtRobotId(obj.getId());
		    				 cd.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(alist.get(i)));
		    				 WatchUserRobot user =listuser.get(1+(int)(Math.random()*280));//随机生成用户
		    				 cd.setUserOpenId(user.getUserOpenId());
		    				 cd.setUserNickName(user.getUserNickName());
		    				 cd.setUserHeadImg(user.getUserHeadImg());
		    				 cd.setUserSex(user.getUserSex());
		    			
		    				 ChatContent cont =contlist.get(1+(int)(Math.random()*contlist.size()-1));//随机生成用户
		    				 cd.setChatType(cont.getChatType());
		    				 cd.setChatContent(cont.getChatContent());
		    				 cd.setIsok("0");
		    				 cd.setLiveId(obj.getLiveId());	
		    				 chatDataService.save(cd);
		    				 
						}
		    				obj.setIsdate("1");
		    				obj.setUpdateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
		    				this.chatRobotService.update(obj);
		    	//生成机器留言数据结束
				mv.setViewName("redirect:/chatData/list?cahtRobotId="+obj.getId());
			}
		
		} catch(Exception e) {
			BaseLog.e(getClass(), "保存异常！", e);
		}
		return mv;
	}
	
	  /** 
     * 获取随机日期 
     * @param beginDate 起始日期，格式为：yyyy-MM-dd HH:mm:ss 
     * @param endDate 结束日期，格式为：yyyy-MM-dd  HH:mm:ss
     * @return 
     */  
    private static Date randomDate(String beginDate,String endDate){  
        try {  
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
            Date start = format.parse(beginDate);  
            Date end = format.parse(endDate);  
              
            if(start.getTime() >= end.getTime()){  
                return null;  
            }  
              
            long date = random(start.getTime(),end.getTime());  
              
            return new Date(date);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return null;  
    }  
      
    private static long random(long begin,long end){  
        long rtn = begin + (long)(Math.random() * (end - begin));  
        if(rtn == begin || rtn == end){  
            return random(begin,end);  
        }  
        return rtn;  
    }  
    
   
}
